package com.sky.lightleafpicturepavilionserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.lightleafpicturepavilionserver.constant.SystemConfigConstant;
import com.sky.lightleafpicturepavilionserver.domain.SystemConfig;
import com.sky.lightleafpicturepavilionserver.dto.SystemConfigDTO;
import com.sky.lightleafpicturepavilionserver.dto.SystemConfigUpdateDTO;
import com.sky.lightleafpicturepavilionserver.service.SystemConfigService;
import com.sky.lightleafpicturepavilionserver.mapper.SystemConfigMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【system_config(系统配置表)】的数据库操作Service实现
* @createDate 2025-09-30 20:16:58
*/
@Slf4j
@Service
public class SystemConfigServiceImpl extends ServiceImpl<SystemConfigMapper, SystemConfig>
    implements SystemConfigService{

    /**
     * 获取所有系统配置
     */
    @Override
    public List<SystemConfigDTO> getAllConfigs() {
        log.info("获取所有系统配置");
        
        List<SystemConfig> configList = this.list();
        
        return configList.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据配置键获取配置值
     */
    @Override
    public String getConfigValue(String configKey) {
        if (!StringUtils.hasText(configKey)) {
            return null;
        }
        
        LambdaQueryWrapper<SystemConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemConfig::getConfigKey, configKey);
        
        SystemConfig config = this.getOne(queryWrapper);
        return config != null ? config.getConfigValue() : null;
    }
    
    /**
     * 根据配置键获取整型配置值
     */
    @Override
    public Integer getIntConfigValue(String configKey, Integer defaultValue) {
        String value = getConfigValue(configKey);
        if (!StringUtils.hasText(value)) {
            return defaultValue;
        }
        
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            log.warn("配置值转换为整型失败，configKey: {}, value: {}", configKey, value);
            return defaultValue;
        }
    }
    
    /**
     * 根据配置键获取布尔型配置值
     */
    @Override
    public Boolean getBooleanConfigValue(String configKey, Boolean defaultValue) {
        String value = getConfigValue(configKey);
        if (!StringUtils.hasText(value)) {
            return defaultValue;
        }
        
        return Boolean.parseBoolean(value);
    }
    
    /**
     * 更新系统配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateConfig(SystemConfigUpdateDTO updateDTO) {
        log.info("更新系统配置，configKey: {}, configValue: {}", 
                updateDTO.getConfigKey(), updateDTO.getConfigValue());
        
        LambdaUpdateWrapper<SystemConfig> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SystemConfig::getConfigKey, updateDTO.getConfigKey())
                .set(SystemConfig::getConfigValue, updateDTO.getConfigValue())
                .set(SystemConfig::getUpdateTime, LocalDateTime.now());
        
        return this.update(updateWrapper);
    }
    
    /**
     * 批量更新系统配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchUpdateConfigs(List<SystemConfigUpdateDTO> updateList) {
        log.info("批量更新系统配置，数量: {}", updateList.size());
        
        for (SystemConfigUpdateDTO updateDTO : updateList) {
            updateConfig(updateDTO);
        }
        
        return true;
    }
    
    /**
     * 初始化默认配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initDefaultConfigs() {
        log.info("初始化默认系统配置");
        
        // 检查配置是否已存在，不存在则创建
        createConfigIfNotExists(SystemConfigConstant.DAILY_SIGN_ENERGY, "5", 
                "每日签到获得的能量", SystemConfigConstant.ConfigType.INT);
        
        createConfigIfNotExists(SystemConfigConstant.WALLPAPER_DOWNLOAD_ENERGY_COST, "1", 
                "下载壁纸消耗的能量", SystemConfigConstant.ConfigType.INT);
        
        createConfigIfNotExists(SystemConfigConstant.HOT_WALLPAPER_VIEW_THRESHOLD, "1000", 
                "热门壁纸浏览量阈值", SystemConfigConstant.ConfigType.INT);
        
        createConfigIfNotExists(SystemConfigConstant.HOT_WALLPAPER_LIKE_THRESHOLD, "100", 
                "热门壁纸点赞量阈值", SystemConfigConstant.ConfigType.INT);
    }
    
    /**
     * 如果配置不存在则创建
     */
    private void createConfigIfNotExists(String configKey, String configValue, 
                                       String description, String type) {
        LambdaQueryWrapper<SystemConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemConfig::getConfigKey, configKey);
        
        SystemConfig existConfig = this.getOne(queryWrapper);
        if (existConfig == null) {
            SystemConfig config = SystemConfig.builder()
                    .configKey(configKey)
                    .configValue(configValue)
                    .description(description)
                    .type(type)
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .build();
            
            this.save(config);
            log.info("创建默认配置: {} = {}", configKey, configValue);
        }
    }
    
    /**
     * 实体转DTO
     */
    private SystemConfigDTO convertToDTO(SystemConfig config) {
        return SystemConfigDTO.builder()
                .configKey(config.getConfigKey())
                .configValue(config.getConfigValue())
                .description(config.getDescription())
                .type(config.getType())
                .build();
    }
}




